package com.ksyun.campus.client;

import java.io.IOException;
import java.io.OutputStream;

public class FSOutputStream extends OutputStream {

    //创建缓冲区
    private final byte[] buffer;
    private int count;

    // 构造函数初始化缓冲区
    public FSOutputStream(int bufferSize) {
        buffer = new byte[bufferSize];
        count = 0;
    }

    @Override
    public void write(int b) throws IOException {
        if (count >= buffer.length) {
            flushBuffer();
        }
        buffer[count++] = (byte) b;
    }

    @Override
    public void write(byte[] b) throws IOException {
        write(b, 0, b.length);
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        if (len < 0 || off < 0 || off + len > b.length) {
            throw new IndexOutOfBoundsException();
        }

        for (int i = 0; i < len; i++) {
            write(b[off + i]);
        }
    }

    @Override
    public void close() throws IOException {
        flushBuffer();  // 确保所有数据被写入
        super.close();
    }
    // 写入缓冲区的内容到实际的输出目标
    private void flushBuffer() throws IOException {
        if (count > 0) {
            // 实际写入操作，假设我们调用某个方法将数据写出
            // writeToOutput(buffer, count);
            count = 0;  // 重置计数器
        }
    }
}
